/**
 * 带token刷新功能的请求工具
 * @param {string} url 
 * @param {GET|POST} method 
 * @param {string/object/ArrayBuffer} data 
 */
const request = (url, method = "GET", data = null) => {
  return new Promise((resolve, reject) => {
    // 从本地存储获取token
    const token = wx.getStorageSync('token');
    
    // 构建请求头
    const header = {
      "Content-Type": method === "POST" 
        ? "application/json;charset=UTF-8" 
        : "application/x-www-form-urlencoded"
    };
    
    // 如果有token，添加到请求头
    if (token) {
      header.token = token;
    }

    // 定义实际请求方法
    const doRequest = (currentToken) => {
      if (currentToken) {
        header.token = currentToken;
      }

      wx.request({
        url: url,
        method: method,
        data: data,
        header: header,
        success: (res) => {
          // 处理token过期的情况 (根据后端实际错误码调整)
          if (res.data.code === 401 || res.data.message === 'TOKEN_IS_OUTOFTIME') {
            // 尝试刷新token
            refreshToken().then(newToken => {
              // 用新token重新请求
              doRequest(newToken).then(resolve).catch(reject);
            }).catch(refreshErr => {
              // 刷新token失败，需要重新登录
              wx.removeStorageSync('token');
              wx.removeStorageSync('userInfo');
              wx.showToast({
                title: '登录已过期，请重新登录',
                icon: 'none'
              });
              // 跳转到登录页
              wx.redirectTo({
                url: '/pages/auth/auth'
              });
              reject(refreshErr);
            });
          } else if (res.statusCode === 200) {
            resolve(res.data);
          } else {
            reject(new Error(`请求失败：${res.statusCode}`));
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    };

    // 发起初始请求
    doRequest(token);
  });
};

// 刷新token的方法
const refreshToken = () => {
  return new Promise((resolve, reject) => {
    // 从本地存储获取refreshToken
    const refreshToken = wx.getStorageSync('refreshToken');
    
    if (!refreshToken) {
      reject(new Error('没有refreshToken'));
      return;
    }

    // 调用刷新token的接口
    wx.request({
      url: 'http://localhost:8082/user/getTokenByRefreshToken',
      method: 'POST',
      data: {
        refreshToken: refreshToken
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.success) {
          // 保存新的token
          const newToken = res.data.data;
          wx.setStorageSync('token', newToken);
          resolve(newToken);
        } else {
          reject(new Error('刷新token失败'));
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
};

module.exports = {
  request
};